<template>
	<view class="content pageBg">
		<nav-bar :header="userInfo.avatar" :score="userInfo.score" :usertype="usertype" :level="level"
			@addScoreClick="addScoreClick" @userInfoClick="userInfoClick" @rankClick="rankClick"></nav-bar>
		<view class="suggest" @click="suggestClick">
			<image class="coin" src="../../static/ic_suggest.png" mode="aspectFill"></image>
		</view>
		<view class="main">
			<view class="item" v-for="(item,index)  in dataList" :key="item" @click="itemClick(item,index)">
				<view class="bg">
					<image :src="item.bg" mode="aspectFill"></image>
					<view class="new" v-if="item.isNew">
						<image src="../../static/ic_new.png" mode="aspectFill"></image>
					</view>
				</view>
				<view class="text">
					{{item.name}}
				</view>
				<view class="score" @click="$emit('addScoreClick')" v-if="usertype!= 1">
					<image class="coin" src="../../static/shouye/ic_coin.png" mode="aspectFill"></image>
					<view class="money">
						50
					</view>
				</view>
			</view>
		</view>
		
		<view>
			<!-- 提示窗示例 -->
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="base" cancelText="取消" confirmText="观看广告修改一次" title="用户信息每个自然月只可以修改一次"
					@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
	

</template>
<script>
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		getUserOpenId
	} from "../../utils/getOpenId";
	import {
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		getTotalUserScore,
		getUserScoreFromCloud,
		saveUserTotalScoreToCloud,
		getUserScore,
		addUserScore,
		saveUserAddScoreToLocal,
		SignInGetScore,
		SignInGetScoreLocal,
		saveUserCloudScoreToLocal
	} from '../../store/scoreManager.js';
	import {
		getTodayDateString,
		getTodayMonthString
	} from '../../utils/common.js';
	import {
		md5
	} from 'js-md5';

	export default {
		data() {
			return {
				alertDialog: null,
				score: 0,
				level: 1,
				dataList: [],
				userInfo: {},
				db: uniCloud.database(),
				usertype: 1,
				isfirst: false,
				videoAd: null,
				interstitialAd: null,
				isNewUser: false
			};
		},
		mounted() {
			this.alertDialog = this.$refs.alertDialog;
		},
		onLoad: function(e) {
			// 在页面onLoad回调事件中创建激励视频广告实例
			if (wx.createRewardedVideoAd) {
				this.videoAd = wx.createRewardedVideoAd({
					adUnitId: 'adunit-b5c90278c107a744'
				});
				this.videoAd.onLoad(() => {});
				this.videoAd.onError((err) => {
					console.error('激励视频光告加载失败', err);
				});
				this.videoAd.onClose((res) => {
					// 用户点击了【关闭广告】按钮
					if (res && res.isEnded) {
						// 正常播放结束，可以下发游戏奖励
						console.log("观看完毕");
						this.userInfo.score = SignInGetScore();
					} else {
						// 播放中途退出，不下发游戏奖励
						console.log("中途退出");
					}
				});
			}
			this.usertype = uni.getStorageSync("userType");
			if (!this.usertype) {
				this.usertype = 1;
			}
			this.isfirst = true;

			// 在页面onLoad回调事件中创建插屏广告实例
			if (wx.createInterstitialAd) {
				this.interstitialAd = wx.createInterstitialAd({
					adUnitId: 'adunit-1722f7e6276cc54a'
				});
				this.interstitialAd.onLoad(() => {});
				this.interstitialAd.onError((err) => {
					console.error('插屏广告加载失败', err);
				});
				this.interstitialAd.onClose(() => {});
			}
		},
		onShow: function() {
			if (this.usertype == 2) { // 正常模式
				this.userInfo.score = getTotalUserScore();

				// 加载抽奖列表
				this.db.collection("guaguale-list").where({
					version: 206
				}).orderBy('index asc').get().then((res) => {
					if (res.result.data && res.result.data.length > 0) {
						this.dataList = res.result.data;
					}
				});

				// 如果不是首次进入 其他页面返回
				if (!this.isfirst) {
					saveUserTotalScoreToCloud().then(() => {
						this.loadHomeAd();
					});
				} else {
					// 首次进入 加载用户信息
					getUserScoreFromCloud().then((user) => {
						if (user && user.score) {
							saveUserCloudScoreToLocal(user.score);
							this.userInfo = user;
						}
						this.userInfo.score = getTotalUserScore();
						this.isfirst = false;
						// 判断用户是否是新用户
						const current = new Date().getTime();
						// 判断是否是新用户的小时数
						const isNewHour = uni.getStorageSync("isNewUser");
						if (!isNewHour) {
							isNewHour = 0;
						}
						if (current - this.userInfo.register_date < isNewHour * 60 * 60 * 1000) {
							this.isNewUser = true;
							console.log("新用户");
						} else {
							console.log("老用户");
							this.isNewUser = false;
						}
					});
				}
			} else { // 提审模式
				this.userInfo.score = getUserScore();
				this.db.collection("guaguale-list").where({
					version: 205
				}).orderBy('index asc').get().then((res) => {
					if (res.result.data && res.result.data.length > 0) {
						this.dataList = res.result.data;
					}
				});
			}
		},
		methods: {
			loadHomeAd: function() {
				const key = "shouyeADCount";
				const count = uni.getStorageSync(key);
				const day = getTodayDateString();
				if (count) {
					const c = count.split("--");
					if (c[0] == day) {
						if (Number(c[1]) < 3) {
							this.loadAD();
							uni.setStorageSync(key, day + "--" + (Number(c[1]) + 1));
						}
					} else {
						this.loadAD();
						uni.setStorageSync(key, day + "--" + 1);
					}
				} else {
					this.loadAD();
					uni.setStorageSync(key, day + "--" + 1);
				}
			},
			loadAD: function() {
				// 在适合的场景显示插屏广告
				if (this.interstitialAd) {
					this.interstitialAd.show().catch((err) => {
						console.error('插屏广告显示失败', err);
					});
				}
			},
			userInfoClick: function() {
				if (this.usertype === 2) {
					// 每个自然月只能修改一次
					const currentMonth = getTodayMonthString();
					if (this.userInfo.updateuserdate && this.userInfo.updateuserdate == currentMonth) {
						this.alertDialog.open();
					} else {
						uni.navigateTo({
							url: '/pages/register/userinfo'
						});
					}
				}
			},
			suggestClick: function(e) {
				// uni.navigateTo({
				// 	url: '/pages/index/suggest?'+ 'usertype=' + usertype
				// })

				uni.navigateTo({
					url: '/pages/detail/detail6'
				});
			},
			dialogConfirm: function() {
				if (this.videoAd) {
					this.videoAd.show().catch(() => {
						// 失败重试
						this.videoAd.load()
							.then(() => this.videoAd.show())
							.catch(err => {
								console.error('激励视频 广告显示失败', err);
								uni.showToast({
									title: '广告拉取失败，请检查网络状况后重试',
									icon: "none",
									duration: 1500
								});
							});
					});
				}
			},
			dialogClose: function() {
				this.alertDialog.close();
			},
			rankClick: function() {
				uni.navigateTo({
					url: '/pages/index/rank?' + '&usertype=' + this.usertype
				});
			},
			addScoreClick: function() {
				// 用户触发广告后，显示激励视频广告
				if (this.usertype === 2) {
					// userInfo.value.score = SignInGetScore()
					if (this.videoAd) {
						this.videoAd.show().catch(() => {
							// 失败重试
							this.videoAd.load()
								.then(() => this.videoAd.show())
								.catch(err => {
									console.error('激励视频 广告显示失败', err);
									uni.showToast({
										title: '广告拉取失败，请检查网络状况后重试',
										icon: "none",
										duration: 1500
									});
								});
						});
					}
				} else {
					this.userInfo.score = SignInGetScoreLocal();
				}
			},
			itemClick: function(item, index) {
				if (this.usertype === 2) {
					if (this.userInfo.score >= 50) {
						this.userInfo.score = saveUserAddScoreToLocal(-50);
						// console.log(item + index);
						const urlStr = '/pages/detail/detail' + (item.type) + '?itemDetail=' + JSON.stringify(item) +
							'&isNewUser=' + this.isNewUser;
						// const urlStr = '/pages/detail/details'+'?itemDetail=' + JSON.stringify(item);
						// url: `/pages/taskDetails/taskDetails?id=${id}`,
						uni.navigateTo({
							url: urlStr
						});
					} else {
						uni.showToast({
							title: '积分不够了',
							icon: "none",
							duration: 1500
						});
					}
				} else {
					// userInfo.value.score = addUserScore(-50);
					// if (userInfo.value.score >= 0) {
					// const urlStr = '/pages/detail/detail5';
					const urlStr = '/pages/detail/detail' + (item.type) + '?title=' + item.name + '&usertype=' + this
						.usertype +
						'&cost=' + item.cost + '&itemDetail=' + JSON.stringify(item);
					uni.navigateTo({
						url: urlStr
					});
					// }
				}
			}
		}
	};
</script>

<style lang="scss">
	@font-face {
		font-family: NumFont;
		src: url('https://mp-02da6b36-ab1b-494d-b346-d6763fb77772.cdn.bspapp.com/resource/font/HONORSans-Bold.ttf');
	}
	


	.main {
		position: relative;
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		row-gap: 50rpx;
		column-gap: 50rpx;
		padding: 50rpx;

		.item {
			width: 300rpx;
			height: 450rpx;
			margin-top: 20rpx;
			position: relative;
			.bg {
				left: 0rpx;
				top: 0rpx;
				image {
					border-radius: 20rpx;
					width: 100%;
					height: 100%;
				}
				.new{
					position: absolute;
					left: 0rpx;
					top: 0rpx;
					border-radius: 10rpx;
					width: 100rpx;
					height: 100rpx;
					image{
						width: 100%;
						height: 100%;
					}
				}
			}

			.text {
				position: absolute;
				text-align: center;
				width: 100%;
				top: 200rpx;
				left: 0;
				color: white;
				font-family: 'NumFont';
				font-size: 60rpx;
				background-color: rgba(0, 0, 0, 0.5);
				font-weight: bold;
			}

			.score {
				position: absolute;
				top: 10rpx;
				right: 10rpx;
				height: 60rpx;
				width: 150rpx;
				align-items: center;
				display: flex;
				flex-direction: row;
				font-size: 20px;
				font-weight: 500;
				margin-left: 30rpx;
				padding: 5rpx 10rpx;
				border-radius: 45rpx;
				background-color: rgba(0, 0, 0, 0.5);
				.coin {
					height: 50rpx;
					width: 50rpx;
				}
				.money {
					color: white;
					margin-left: 20rpx;
					margin-right: 20rpx;
				}
			}
		
		}
	}

	.header {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 166rpx;
		background-color: transparent;
		/* background-color: black; */
		display: flex;
		flex-direction: row;
		align-items: bottom;

		.level {
			bottom: 10rpx;
			height: 60rpx;
			color: black;
		}

	}

	.content {
		position: absolute;
		width: 100%;
		height: 100%;

		/* background-image: url("/static/bg.png");
		background-size: cover; */
	}
	
	

	.bg {
		position: absolute;
		width: 100%;
		height: 100%;
	}
	
	.suggest{
		z-index: 1000;
		position: fixed;
		bottom: 100rpx;
		right: 50rpx;
		width: 100rpx;
		height: 100rpx;
		image{
			width: 100%;
			height: 100%;
		}
	}

</style>